<?php
$root = $_SERVER['DOCUMENT_ROOT'];
include($root . "/util/session.php"); //checks that the user is logged in
include($root . "/util/privilege_check.php");
checkPrivilege("teacher");

if (isset($_POST['startDate']) && isset($_POST['endDate']) && isset($_POST['startTime']) && isset($_POST['endTime']) && isset($_POST['questionNumber'])) {
    $startDate = $_POST['startDate'];
    $endDate = $_POST['endDate'];
    $startTime = $_POST['startTime'];
    $endTime = $_POST['endTime'];

    $start = date('Y-m-d H:i:s', strtotime($startDate . ' ' . $startTime));
    $end = date('Y-m-d H:i:s', strtotime($endDate . ' ' . $endTime));

    if ($end < $start) {        
       $_SESSION['error'] = 1;
    } else if ($start < date('Y-m-d H:i:s')) { 
        $_SESSION['error'] = 2;
    } else {
        $questionNumber = $_POST['questionNumber'];
        if (isset($_POST['revision'])) {
            $revision = 1;
        } else {
            $revision = 0;
        }
        $subjectID = $_SESSION['subjectPanel'];
        $chapterID = $_SESSION['chapterPanel'];


        $sql_test = "SELECT * FROM tests WHERE chapterID = $chapterID AND subjectID = '$subjectID'";
        $result = mysqli_query($db, $sql_test);
        $row = mysqli_fetch_assoc($result);
        if ($row) {
            $sql = "UPDATE tests SET startDate='$start', endDate='$end', revisionAllowed='$revision', numQuestions='$questionNumber' 
            WHERE chapterID = $chapterID AND subjectID = '$subjectID'";
        } else {
            $sql = "INSERT INTO tests (chapterID, subjectID, startDate, endDate, revisionAllowed, numQuestions) 
            VALUES ('$chapterID', '$subjectID', '$start' , '$end', '$revision', '$questionNumber')";
        }


        if (mysqli_query($db, $sql)) {
            mysqli_close($db);
            header("Location: ../teacher.php");
        } else {
            echo "Error: " . $sql . "<br>" . mysqli_error($db);
        }
    }
    header("Location: ../teacher.php");
}
